/**
 * 指针目标编辑接口测试用例
 *
 * Created by snowingsea on 2020/03/07.
 */
const chai = require('chai');
const should = chai.should(); // eslint-disable-line no-unused-vars
chai.use(require('chai-http'));
const randomstring = require('randomstring');

const common = require('./../../../common');
const Administrator = require('./../../../../models/administrator');
const uri = require('./../../uri');
const benchmark = require('./../../../../benchmark/analyse-files/logic_bombs');

module.exports = describe('/PUT functions/:id/malloc/:name.json', function () {
  const administrator = new Administrator();
  const newUserIds = [];
  let projectVersion = {};
  let existsVariableName;
  let func = {};
  function url(functionId, variableName) {
    return `/functions/${functionId}/malloc/${variableName}.json`;
  }

  before(function (done) {
    administrator.login()
      .then(() => administrator.createRandomTester())
      .then((tester) => {
        newUserIds.push(tester.userId);
        return tester.createRandomProject();
      })
      .then((project) => project.createRandomVersion())
      .then((res) => {
        projectVersion = res;
        return projectVersion.getAllFunctions(benchmark);
      })
      .then(([item]) => {
        func = item;
        done();
      })
      .catch(done);
  });
  after(function (done) {
    administrator.removeUsers(newUserIds)
      .then(() => {
        done();
      })
      .catch(done);
  });

  common.should.be.user(uri, url, 'put');
  common.should.be.tester(uri, url, 'put');

  // 正常编辑
  [
    {},
    { typeName: randomstring.generate({ length: 16, charset: 'alphabetic' }) },
    { elementTypeName: randomstring.generate({ length: 16, charset: 'alphabetic' }), length: Math.floor(Math.random() * 10 + 1) },
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }) },
    { variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }), typeName: randomstring.generate(3) },
    {
      variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }),
      elementTypeName: randomstring.generate({ length: 16, charset: 'alphabetic' }),
      length: Math.floor(Math.random() * 10 + 1),
    },
  ].forEach((variable, index) => {
    it(`it should ${index === 0 ? 'PUT' : 'put'} malloc variable with ${JSON.stringify(variable)}`, function (done) {
      const originVariableName = randomstring.generate({ length: 16, charset: 'alphabetic' });
      existsVariableName = variable.variableName;
      func.addMallocVariable(originVariableName, { typeName: 'int' })
        .then(() => projectVersion.project.creator.login())
        .then(() => {
          chai.request(uri)
            .put(url(func.functionId, originVariableName))
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .send(variable)
            .end((err, res) => {
              res.should.have.status(200);
              common.should.be.functionMallocVariableMessage(res.body);
              Object.keys(variable).forEach((key) => {
                res.body[key].should.be.eql(variable[key]);
              });

              if (variable.variableName) {
                // 查询
                chai.request(uri)
                  .get(url(func.functionId, originVariableName))
                  .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
                  .end((err, res) => {
                    res.should.have.status(404);
                    common.should.be.errorMessage(res.body);
                    done();
                  });
              } else {
                done();
              }
            });
        })
        .catch(done);
    });
  });

  // 将变量名改成一样的名字
  it('it should put malloc variable with same variable name', function (done) {
    const variableName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    func.addMallocVariable(variableName, { typeName: 'int' })
      .then(() => projectVersion.project.creator.login())
      .then(() => {
        chai.request(uri)
          .put(url(func.functionId, variableName))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({ variableName })
          .end((err, res) => {
            res.should.have.status(200);
            common.should.be.functionMallocVariableMessage(res.body);
            res.body.variableName.should.be.eql(variableName);
            done();
          });
      })
      .catch(done);
  });

  // 缺少参数
  [
    { elementTypeName: 'int' },
    { length: 10 },
  ].forEach((variable) => {
    it(`it should fail to put malloc variable with ${JSON.stringify(variable)}`, function (done) {
      const variableName = randomstring.generate({ length: 16, charset: 'alphabetic' });
      func.addMallocVariable(variableName, { typeName: 'int' })
        .then(() => projectVersion.project.creator.login())
        .then(() => {
          chai.request(uri)
            .put(url(func.functionId, variableName))
            .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
            .send(variable)
            .end((err, res) => {
              res.should.have.status(400);
              common.should.be.errorMessage(res.body);
              done();
            });
        })
        .catch(done);
    });
  });

  // 同一个函数中指针目标不允许重名
  it('it should fail to add malloc variable when the variable is exists', function (done) {
    const existName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    const variableName = randomstring.generate({ length: 16, charset: 'alphabetic' });
    func.addMallocVariable(existName, { typeName: 'int' })
      .then(() => func.addMallocVariable(variableName, { typeName: 'int' }))
      .then(() => projectVersion.project.creator.login())
      .then(() => {
        chai.request(uri)
          .put(url(func.functionId, variableName))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({ variableName: existName })
          .end((err, res) => {
            res.should.have.status(409);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可编辑不存在的指针目标
  it('it should fail to put malloc variable when the variable is not exists', function (done) {
    chai.request(uri)
      .put(url(func.functionId, randomstring.generate({ length: 16, charset: 'alphabetic' })))
      .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
      .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }) })
      .end((err, res) => {
        res.should.have.status(404);
        common.should.be.errorMessage(res.body);
        done();
      });
  });

  // 不可编辑不存在的函数的指针目标
  it('it should fail to put malloc variable when the function is not exists', function (done) {
    new Promise((resolve) => {
      chai.request(uri)
        .put(url('000000000000000000000000', randomstring.generate({ length: 16, charset: 'alphabetic' })))
        .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
        .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }) })
        .end((err, res) => {
          res.should.have.status(404);
          common.should.be.errorMessage(res.body);
          resolve();
        });
    })
      .then(done)
      .catch(done);
  });

  // 不可编辑他人项目的函数指针目标
  it('it should fail to put malloc variable when the project is not yours', function (done) {
    let newUser;
    administrator.createRandomTester()
      .then((tester) => {
        newUserIds.push(tester.userId);
        newUser = tester;
        return tester.getToken();
      })
      .then(() => {
        chai.request(uri)
          .put(url(func.functionId, randomstring.generate({ length: 16, charset: 'alphabetic' })))
          .set('Authorization', `Bearer ${newUser.token.accessToken}`)
          .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }) })
          .end((err, res) => {
            res.should.have.status(404);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可编辑冻结的项目版本的指针变量
  it('it should fail to put malloc variable when the project version is frozen', function (done) {
    projectVersion.project.freezeVersion(projectVersion.versionId)
      .then(() => {
        chai.request(uri)
          .put(url(func.functionId, existsVariableName))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }) })
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });

  // 不可编辑冻结的项目指针变量
  it('it should fail to put malloc variable when the project is frozen', function (done) {
    projectVersion.project.creator.freezeProject(projectVersion.project.projectId)
      .then(() => {
        chai.request(uri)
          .put(url(func.functionId, existsVariableName))
          .set('Authorization', `Bearer ${projectVersion.project.creator.token.accessToken}`)
          .send({ variableName: randomstring.generate({ length: 16, charset: 'alphabetic' }) })
          .end((err, res) => {
            res.should.have.status(403);
            common.should.be.errorMessage(res.body);
            done();
          });
      })
      .catch(done);
  });
});
